﻿Imports System.Data.OleDb
Imports System.Data
Imports System.Globalization
Imports System.Globalization.CultureInfo
Imports System.IO
Imports Subgurim.Controles
Public Class calendar
    Inherits System.Web.UI.Page
    Sub Page_Load(o As Object, e As EventArgs)
        If User.Identity.IsAuthenticated = False Then
            Response.Redirect("~/Account/Register.aspx")
        End If
        Dim startDate As DateTime = New DateTime(cal1.VisibleDate.Year, cal1.VisibleDate.Month, 1).AddDays(-7)
        Dim endDate As DateTime = New DateTime(cal1.VisibleDate.Date.AddMonths(1).Year, cal1.VisibleDate.Date.AddMonths(1).Month, 1).AddDays(7)
        cal1.DataSource = GetEventData(startDate, endDate)
        If Not IsPostBack Then
            cal1.SelectedDate = DateTime.Now.Date
            GMap1.Visible = False
            BindEventListing()
        End If
    End Sub
    Function GetConnection() As OleDbConnection
        Dim con As OleDbConnection = New OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
        Return con
    End Function


    Function GetEventData(startDate As DateTime, endDate As DateTime) As DataTable
        '--We'll avoid using a session variable this time and
        '--query the database each time the page is called;
        '--However, we'll make sure we're only loading events for the
        '--currently displayed month (plus the week before and week after)

        '--read data from an Access query
        Dim con As OleDbConnection = GetConnection()
        Dim cmd As OleDbCommand = New OleDbCommand()
        cmd.Connection = con
        Session("currentuser") = User.Identity.Name
        cmd.Parameters.AddWithValue("@currentUser", Session("currentuser"))
        cmd.CommandText = String.Format("Select EventDate, CreatedBy, Count(*) From EventInfo Where (CreatedBy = ?) and EventDate >= #{0}# And EventDate <= #{1}# Group By EventDate,CreatedBy", _
                                        startDate, endDate)
        Dim ds As DataSet = New DataSet()
        Dim da As OleDbDataAdapter = New OleDbDataAdapter(cmd)
        da.Fill(ds)
        con.Close()

        Return ds.Tables(0)
    End Function

    Function GetEventListing(selectedDay As DateTime) As DataTable
        '--read event listing for the given day from an Access query
        Dim con As OleDbConnection = GetConnection()
        Dim cmd As OleDbCommand = New OleDbCommand()
        cmd.Connection = con
        Session("currentuser") = User.Identity.Name
        cmd.Parameters.AddWithValue("@currentUser", Session("currentuser"))
        cmd.CommandText = String.Format("Select * from EventInfo Where (CreatedBy = ?) and EventDate >= #{0}# And EventDate < #{1}#", _
                                        selectedDay.ToString("MM/dd/yyyy"), _
                                        selectedDay.AddDays(1).ToString("MM/dd/yyyy"))
        Dim ds As DataSet = New DataSet()
        Dim da As OleDbDataAdapter = New OleDbDataAdapter(cmd)
        da.Fill(ds)
        con.Close()

        Return ds.Tables(0)
    End Function


    Sub BindEventListing()
        Dim dt As DataTable = GetEventListing(cal1.SelectedDate)
        dg.DataSource = dt
        dg.DataBind()
        lblDate.Text = cal1.SelectedDate.ToString("d")
        lblNoEvents.Visible = (dt.Rows.Count = 0)
    End Sub


   


    Sub MonthChange(o As Object, e As MonthChangedEventArgs)
        '--triggered when the month in the calendar changes
        '--requery the database for the new month's events
        Dim startDate As DateTime = e.NewDate.AddDays(-7)
        Dim endDate As DateTime = e.NewDate.AddMonths(1).AddDays(7)
        cal1.DataSource = GetEventData(startDate, endDate)
    End Sub

    Sub SelectionChange(o As Object, e As EventArgs)
        BindEventListing()
    End Sub

    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If String.IsNullOrEmpty(lb_showcoordinates.Text) Then
            nocoordinatesmessage.Text = "Please enter your meeting location above <i>(Required)</i>"
            Return
        End If
        Dim conn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
        conn.Open()
        Dim cmd As New OleDbCommand("INSERT INTO Events (EventTitle, EventDescription, EventDate, EventCategory, CreatedBy, StreetAddress, Town, Country, Coordinates) VALUES (@f1,@f2,@f3,@f4,@f5,@f6,@f7,@f8,@f9)", conn)
        cmd.Parameters.AddWithValue("@f1", tb_eventtitle.Text)
        cmd.Parameters.AddWithValue("@f2", tb_eventdescription.Text)
        cmd.Parameters.AddWithValue("@f3", DateTime.ParseExact(tb_eventdate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture))
        cmd.Parameters.AddWithValue("@f4", dd_eventcategory.SelectedIndex + 1)
        cmd.Parameters.AddWithValue("@f5", User.Identity.Name)
        cmd.Parameters.AddWithValue("@f6", txtStreetAddress.Text)
        cmd.Parameters.AddWithValue("@f7", txtSuburb.Text)
        cmd.Parameters.AddWithValue("@f8", txtCountry.Text)
        cmd.Parameters.AddWithValue("@f9", lb_showcoordinates.Text)
        cmd.ExecuteNonQuery()
        conn.Close()
        Response.Redirect("calendar.aspx")
    End Sub
    Public Sub lnkShowMap_Click(ByVal sender As Object,
        ByVal e As System.EventArgs) Handles lnkShowMap.Click
        Dim strFullAddress As String
        Dim sMapKey As String =
        ConfigurationManager.AppSettings("googlemaps.subgurim.net")
        Dim GeoCode As Subgurim.Controles.GeoCode

        ' Combine our address fields to create the full address.  The street,
        ' suburb and country should be seperated by  periods (.)
        strFullAddress = txtStreetAddress.Text & ". " & txtSuburb.Text & ". " & txtCountry.Text

        ' Work out the longitude and latitude
        GeoCode = GMap1.geoCodeRequest(strFullAddress, sMapKey)
        Dim gLatLng As New Subgurim.Controles.GLatLng(GeoCode.Placemark.coordinates.lat,
            GeoCode.Placemark.coordinates.lng)
        ' Display the map
        GMap1.setCenter(gLatLng, 16, Subgurim.Controles.GMapType.GTypes.Normal)
        Dim oMarker As New Subgurim.Controles.GMarker(gLatLng)
        GMap1.addGMarker(oMarker)

        ' Create coordinates in stored mem ' 
        Dim coordinates As GLatLng = GeoCode.Placemark.coordinates
        lb_showcoordinates.Text = coordinates.ToString
    End Sub


End Class